package client.view;


import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import jdk.internal.org.objectweb.asm.tree.IntInsnNode;
import javafx.scene.control.MenuItem;

import model.Message;
import model.MsgType;

import java.awt.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.AbstractMap;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.table.TableStringConverter;

import com.google.gson.Gson;
import com.sun.javafx.scene.EnteredExitedHandler;
import com.sun.org.apache.bcel.internal.generic.NEW;

import client.ChatGPT;
import client.MessageSender;
import client.main.Client_main;
import client.service.HandleMessage;

// 聊天界面，点击“消息记录”按钮即可显示聊天记录，再次点击即可切换回图片

public class MachineChat extends Application {

     private BorderPane cardLayout;//卡片布局
     private Pane panel_north;//北部区域面板
     // private Label jbl_touxiang;//头像
     private Label jbl_friendname;//好友名称
     private Button btn_exit, btn_min;//最小化和关闭按钮

     private Pane panel_south;//南部区域面板
     private TextArea jtp_input;//消息输入区
     private Button btn_pic;//图片按钮
     private Button btn_send, btn_close;//消息输入区下方关闭和发送按钮
     // private Pane panel_east;//东部面板

     private String myName;
     private int userId = 1;
     
     private Text text;
     private HBox msgBox;
     private VBox msg;
     private VBox chatBox;
     
     // 通信逻辑
     private ChatGPT chatGPT;
     
     private String prefix = "file:image/dialogimage/";
     
    
   public MachineChat(int userId, String myName) {

       this.userId = userId;
       this.myName = myName;
       
 //      df = new SimpleDateFormat("yyyy-MM-dd a hh:mm:ss");
     // 还要连接socket

   }
   

     private class PhotoMenuItem extends MenuItem {
    	    private Image photo;

    	    public PhotoMenuItem(String url) {
    	        this.photo = new Image(url);
    	        ImageView imageView = new ImageView(photo);
    	        imageView.setFitWidth(50);
    	        imageView.setFitHeight(50);
    	        setGraphic(imageView);
	            
    	        // 点击事件处理
    	        setOnAction(e -> {
    	            // 在此处理照片的发送逻辑
    	            System.out.println("发送照片: " + url);
    	            showMyPic(url, getTime());
    	            storeMessage(url, 0);
    	            // 处理表情包的传输
    	            if(url.equals(prefix + "1.jfif"))
    	            	chatGPT.setUserPrompt("我向你发送了表示开心的表情包");
    	            else if(url.equals(prefix + "2.jfif"))
    	            	chatGPT.setUserPrompt("我向你发送了表示你很棒的表情包");
    	            else if(url.equals(prefix + "3.jfif"))
    	            	chatGPT.setUserPrompt("我向你发送了表示亲切的表情包");
    	            else if(url.equals(prefix + "4.jfif"))
    	            	chatGPT.setUserPrompt("我向你发送了表示我很开心的表情包");
    	            else
    	            	chatGPT.setUserPrompt("我向你发送了表示很厉害的表情包");
    	            
    	            // 在后台线程执行异步操作
    	            new Thread(() -> {
    	                String reply = chatGPT.chat();
    	                storeMessage(reply, 1);
    	                // 在主线程上更新UI
    	                Platform.runLater(() -> {
    	                    showFriendMsg(reply, getTime());
    	                });
    	            }).start();
    	        });
    	    }
    	}
     
     
    @Override
    public void start(Stage primaryStage) {
        primaryStage.getIcons().add(new Image("file:image/login/Q.png"));
        primaryStage.setTitle("ChatBox");


        cardLayout = new BorderPane();
        cardLayout.setPrefSize(800, 600);
        cardLayout.setVisible(true);//设置窗体可见

        Scene scene = new Scene(cardLayout);

        //北部面板
        panel_north = new Pane();
        panel_north.setPrefWidth(800);
        panel_north.setPrefHeight(70);
        cardLayout.setTop(panel_north);




//      //左上角灰色头像
        ImageView jbl_touxiang = new ImageView(new Image("file:image/dialogimage/chatGPT.jpg"));
        jbl_touxiang.setLayoutX(5);
        jbl_touxiang.setLayoutY(5);
        jbl_touxiang.setFitWidth(60);
        jbl_touxiang.setFitHeight(60);
        panel_north.getChildren().add(jbl_touxiang);

        //头像右方正在聊天的对方姓名
        jbl_friendname = new Label("ChatGPT");
        jbl_friendname.setLayoutX(320);
        jbl_friendname.setLayoutY(20);
        jbl_friendname.setPrefWidth(300);
        jbl_friendname.setPrefHeight(20);
        jbl_friendname.setFont(Font.font("Arial", FontWeight.BOLD, 24));
        panel_north.getChildren().add(jbl_friendname);

        //右上角最小化按钮
        btn_min=new Button();
        ImageView imageView1 = new ImageView(new Image("file:image/dialogimage/min.png"));
        btn_min.setGraphic(imageView1);
        btn_min.setOnAction(e -> primaryStage.setIconified(true));
        btn_min.setLayoutX(740);
        btn_min.setLayoutY(0);
        btn_min.setMaxWidth(50);
        btn_min.setMaxHeight(50);
        btn_min.setPadding(new Insets(0));
        panel_north.getChildren().add(btn_min);

        //右上角关闭按钮
        btn_exit = new Button();
        ImageView imageView2 = new ImageView(new Image("file:image/dialogimage/exit.jpg"));
        btn_exit.setGraphic(imageView2);
        btn_exit.setLayoutX(770);
        btn_exit.setLayoutY(0);
        btn_exit.setMaxWidth(50);
        btn_exit.setMaxHeight(50);
        btn_exit.setOnAction(e -> primaryStage.close());
        btn_exit.setPadding(new Insets(0));
        panel_north.getChildren().add(btn_exit);

        //设置北部面板背景色
        panel_north.setStyle("-fx-background-color: #169AE4;"); // 设置背景颜色
     
        //中部聊天内容显示部分
        chatBox = new VBox(); // 创建垂直布局容器
        chatBox.setSpacing(20);
        HBox spaceBox = new HBox();
        chatBox.getChildren().add(spaceBox);
        
        // 将消息添加到垂直布局容器中
        ScrollPane scrollPane_Msg = new ScrollPane(chatBox); // 创建包含消息的滚动窗格
        scrollPane_Msg.setLayoutX(0);
        scrollPane_Msg.setLayoutY(0);
        scrollPane_Msg.setMinSize(800,500);
        scrollPane_Msg.vvalueProperty().bind(chatBox.heightProperty()); // 将vvalue属性绑定到chatBox的高度
        cardLayout.setCenter(scrollPane_Msg);
                
        
        //南部面板
        panel_south = new Pane();
        panel_south.setLayoutX(0);
        panel_south.setLayoutY(0);
        panel_south.setPrefWidth(800);
        panel_south.setPrefHeight(190);
        cardLayout.setBottom(panel_south);

        //内容输入区
        jtp_input = new TextArea();
        jtp_input.setWrapText(true); // 启用自动换行
        jtp_input.setStyle("-fx-font-size: 18px; -fx-text-fill: #000000;");
        jtp_input.setLayoutX(0);
        jtp_input.setLayoutY(30);
        jtp_input.setMaxWidth(800);
        jtp_input.setMinWidth(800);
        jtp_input.setPrefHeight(130);
        //添加到南部面板
        panel_south.getChildren().add(jtp_input);

        //图片按钮
        btn_pic = new Button();
        ImageView imageView3 = new ImageView(new Image("file:image/dialogimage/biaoqing.png"));
        btn_pic.setGraphic(imageView3);
        btn_pic.setMaxSize(20, 20);
        btn_pic.setMinSize(20, 20);
        btn_pic.setOnAction(e -> {
            // 创建菜单项
            PhotoMenuItem emojiItem1 = new PhotoMenuItem("file:image/dialogimage/1.jfif");
            PhotoMenuItem emojiItem2 = new PhotoMenuItem("file:image/dialogimage/2.jfif");
            PhotoMenuItem emojiItem3 = new PhotoMenuItem("file:image/dialogimage/3.jfif");
            PhotoMenuItem emojiItem4 = new PhotoMenuItem("file:image/dialogimage/4.jfif");
            PhotoMenuItem emojiItem5 = new PhotoMenuItem("file:image/dialogimage/5.jfif");

            // 创建ContextMenu
            ContextMenu contextMenu = new ContextMenu(emojiItem1, emojiItem2, emojiItem3, emojiItem4, emojiItem5);

            // 关联ContextMenu与按钮
            contextMenu.show(btn_pic, Side.TOP, 0, 0);
        });

        btn_pic.setLayoutX(5);
        btn_pic.setLayoutY(5);
        panel_south.getChildren().add(btn_pic);
        



        //消息关闭按钮
        btn_close = new Button();
        ImageView imageView4 = new ImageView(new Image("file:image/dialogimage/close.jpg"));
        btn_close.setGraphic(imageView4);
        btn_close.setLayoutX(640);
        btn_close.setLayoutY(160);
        btn_close.setPrefWidth(55);
        btn_close.setPrefHeight(25);
        btn_close.setOnAction(e->clear(e));
        panel_south.getChildren().add(btn_close);

        //消息发送按钮
        btn_send = new Button();
        ImageView imageView5 = new ImageView(new Image("file:image/dialogimage/send.jpg"));
        btn_send.setGraphic(imageView5);
        btn_send.setLayoutX(720);
        btn_send.setLayoutY(160);
        btn_send.setPrefWidth(55);
        btn_send.setPrefHeight(25);
        btn_send.setOnAction(e->sendAndGet(e));
        panel_south.getChildren().add(btn_send);

        primaryStage.setScene(scene);
        primaryStage.show();
        
        // 以下进行逻辑处理
        initHistory();
    }

    public void showFriendMsg(String msgString, String time) {
        msgBox = new HBox();
        msg = new VBox();
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        Region space1 = new Region();
        space1.setMaxWidth(20);
        space1.setMinWidth(20);
        // 创建好友发送消息的 HBox，并设置样式和对齐方式
        Text info = new Text("ChatGPT" + "   " + time);
        info.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #8F1000; -fx-font-size: 20px;");
        info.setTextAlignment(TextAlignment.LEFT);
        info.setFill(Color.DARKVIOLET);
        text = new Text(msgString);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 25px;");
        msg.getChildren().addAll(info, text);
        msgBox.getChildren().addAll(space1, msg);
        chatBox.getChildren().add(msgBox);
    }
    
    public void showMyMsg(String msgString, String time) {
    	HBox msgBox = new HBox();
        VBox msg = new VBox();
        Region space2 = new Region();
        space2.setMaxWidth(250);
        space2.setMinWidth(250);
        // 创建我发送消息的 HBox，并设置样式和对齐方式
        Text info  = new Text(myName + "   " + time);
        info.setWrappingWidth(520);
        info.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #8F1000; -fx-font-size: 20px;");
        info.setTextAlignment(TextAlignment.RIGHT);
        info.setFill(Color.DARKGOLDENROD);
        text= new Text(msgString);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 25px;");
        text.setTextAlignment(TextAlignment.RIGHT);
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        msg.getChildren().addAll(info, text);
        msgBox.getChildren().addAll(space2, msg);
        chatBox.getChildren().add(msgBox); 
    }
    
    public void showMyPic(String url, String time) {
    	System.out.println(url);
    	// 信息发送
    	HBox msgBox1 = new HBox();
        VBox msg1 = new VBox();
        Region space3 = new Region();
        space3.setMaxWidth(250);
        space3.setMinWidth(250);
        // 创建我发送消息的 HBox，并设置样式和对齐方式
        text= new Text(myName + "   " + time);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 20px;");
        text.setTextAlignment(TextAlignment.RIGHT);
        text.setFill(Color.DARKGOLDENROD);
        msg1.setMaxWidth(530);
        msg1.setMinWidth(530);
        msg1.getChildren().add(text);
        msgBox1.getChildren().addAll(space3, msg1);
        chatBox.getChildren().add(msgBox1); 
    	
    	// 照片发送
    	HBox msgBox = new HBox();
        VBox msg = new VBox();
        Region space2 = new Region();
        space2.setMaxWidth(550);
        space2.setMinWidth(550);
        // 照片
        ImageView imageView = new ImageView(new Image(url));
        imageView.setFitWidth(200);
        imageView.setPreserveRatio(true);
        imageView.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px;");
        imageView.setSmooth(true);
        imageView.setCache(true);
        msg.setMaxWidth(200);
        msg.setMinWidth(200);
        msg.getChildren().add(imageView);
        msgBox.getChildren().addAll(space2, msg);
        chatBox.getChildren().add(msgBox); 
    }
    
    public void showFriendPic(String url, String time) {
    	// 信息
        msgBox = new HBox();
        msg = new VBox();
        msg.setMaxWidth(530);
        msg.setMinWidth(530);
        Region space1 = new Region();
        space1.setMaxWidth(20);
        space1.setMinWidth(20);
        // 创建本人发送消息的 HBox，并设置样式和对齐方式
        text = new Text(time);
        text.setWrappingWidth(520);
        text.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px; -fx-text-fill: #FFFFFF; -fx-font-size: 20px;");
        text.setFill(Color.DARKVIOLET);
        msg.getChildren().add(text);
        msgBox.getChildren().addAll(space1, msg);
        chatBox.getChildren().add(msgBox);
        
    	// 照片发送
    	HBox msgBox1 = new HBox();
        VBox msg1 = new VBox();
        msg1.setMaxWidth(530);
        msg1.setMinWidth(530);
        Region space3 = new Region();
        space3.setMaxWidth(20);
        space3.setMinWidth(20);
        // 照片
        ImageView imageView = new ImageView(new Image(url));
        imageView.setFitWidth(200);
        imageView.setPreserveRatio(true);
        imageView.setStyle("-fx-background-color: #8BC34A; -fx-padding: 10px;");
        imageView.setSmooth(true);
        imageView.setCache(true);
        msg.setMaxWidth(200);
        msg.setMinWidth(200);
        msg.getChildren().add(imageView);
        msgBox1.getChildren().addAll(space3, msg1);
        chatBox.getChildren().add(msgBox1);
    }
    
    public void sendAndGet(ActionEvent e) {
    	String msg = jtp_input.getText();
    	showMyMsg(msg, getTime());
    	storeMessage(msg, 0);
		jtp_input.clear();
		
		chatGPT.setUserPrompt(msg);
        // 在后台线程执行异步操作
        new Thread(() -> {
            String reply = chatGPT.chat();
            storeMessage(reply, 1);
            // 在主线程上更新UI
            Platform.runLater(() -> {
                showFriendMsg(reply, getTime());
            });
        }).start();
    }
    
    public void clear(ActionEvent e) {
    	jtp_input.clear();
    }

    public String getTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }
   
    public void initHistory() {
    	// 连接逻辑暂时在这里搞
    	chatGPT = new ChatGPT();
		String host = "127.0.0.1";
		int port = 12345;
		try {
			Socket client = new Socket(host, port);
			DataInputStream dis = new DataInputStream(client.getInputStream());
			DataOutputStream dos = new DataOutputStream(client.getOutputStream());
			Vector<model.Message> history = new HandleMessage(dis, dos).initMachineHistory(userId); 
			for(int i = 0; i < history.size(); i++) {
				int talkerId = history.elementAt(i).getRoomID();
				String text = history.elementAt(i).getText();
				String time = history.elementAt(i).getTime();
    		
				if(talkerId == 0) { // 我的消息
					chatGPT.setUserPrompt(text);
					if(text.startsWith(prefix)) // 照片
						showMyPic(text, time);
					else // 文本
						showMyMsg(text, time);
				} else { // 别人的
					chatGPT.setAssitantPrompt(text);
					showFriendMsg(text, time);
				}
			}
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
    }
    
    
    public void storeMessage(String mes, int isMachine) {
		String host = Client_main.ip;
		int port = 12345;
		try {
			Socket client = new Socket(host, port);
			DataOutputStream dos = new DataOutputStream(client.getOutputStream());
			new MessageSender(dos, userId).MachineSend(mes, isMachine);	
			client.close();
		} catch (Exception e) {
			// TODO: handle exception
		}	
    }
    
    public static void main(String args[]) {
    	launch(args);
    }
}